<template>
	<div class="content">
		<div class="left">
			<div class="sec-title">点位选择</div>
			<div style="margin-bottom: 10px;">
				<span>已选({{ selectedData.length + '/' + tableData.length }})</span>
			</div>
			<Table
				:columns="columns"
				:data="tableData"
				:showPage="false"
				@on-selection-change="onSelectChange"
				height="680">
				<template slot-scope="{ row, index }" slot="action">
					<a @click.stop="onDelete(row, index)">删除</a>
				</template>
			</Table>
		</div>
		<div class="right">
			<div class="map-content">
				<div ref="map" id="map"></div>
				<div class="flex bm-control">
					<Select style="width: 100px" v-model="editType" @on-change="editTypeChange">
					  <Option value="rectTool">矩形选点</Option>
					  <Option value="circleTool">圆形选点</Option>
					  <Option value="polygonTool">多边形选点</Option>
					</Select>
					<Checkbox class="drawToggle" v-model="draw" @on-change="drawChange">开启绘制</Checkbox>
					<span class="clear-btn" @click="onClear">
						<img src="./img/clear.svg">
					</span>
				</div>
				<div v-show="false">
					<div ref="wInfo" class="w-info">
						<ul>
							<li class="t-name">
								<Icon type="ios-search"></Icon>
								<span class="w-text">{{ windowInfo.name }}</span>
							</li>
							<li>
								<img src="./img/id.svg" style="width: 18px;">
								<span class="w-text">{{ windowInfo.id }}</span>
							</li>
							<li>
								<img src="./img/building.svg" style="width: 18px;">
								<span class="w-text">{{ windowInfo.address }}</span>
							</li>
							<li>
								<img src="./img/pin.svg" style="width: 18px;">
								<span class="w-text">{{ windowInfo.lnglat.lng + ',' + '\n' + windowInfo.lnglat.lat }}</span>
							</li>
						</ul>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<script>
export default {
  data () {
    return {
      loading: false,
			editType: 'rectTool',
			lastDrawType: 'rectTool',
			tableData: [],
			columns: [
				{
					type: 'selection',
					width: 50,
					align: 'center'
				},
				{
					type: 'index',
					title: '序号',
					width: 60,
					align: 'center'
				},
			  {
			    title: '点位名称',
			    key: 'name'
			  }
			],
			selectedData: [],
			map: null,
			windowInfo: {
				name: '',
				id: '',
				address: '',
				lnglat: {
					lng: '',
					lat: ''
				}
			},
			rectTool: null,
			circleTool: null,
			polygonTool: null,
			draw: false,
			markerMap: null,
			currentMarker: null,
			defaultIcon: new T.Icon.Default(),
			// defaultIcon: new T.Icon({
			// 	iconUrl: require('./img/marker-icon.png'),
			// 	iconSize: new T.Point(25, 41),
			// 	iconAnchor: new T.Point(12, 41)
			// }),
			markerList: [],
			selectMarkers: []
    }
  },
  mounted () {
		this.initMap()
	},
  methods: {
		onClear() {
			const drawType = this.editType
			this[drawType].clear()
			this.resetData()
			this.selectMarkers.forEach(item =>{
				if(item.getIcon().options.id){
					item.setIcon(this.defaultIcon)
				}
			})
			this.selectMarkers = []
		},
		resetData() {
			this.tableData = []
			this.selectedData = []
		},
		// 测试数据
		addTestData() {
			const arrayObj = []
			this.markerList = []
			const data = {
				name: '名称',
				id: 'id_',
				address: '',
				lnglat: {},
			}
			for (let i = 0; i < 500; i++) {
				let obj = {	...data }
				obj.name = data.name + i
				obj.id = data.id + i
				const marker = new T.Marker(new T.LngLat(Math.random() * 40 + 85, Math.random() * 30 + 21), obj);
				marker.addEventListener('click', (e) => {
					console.log(e)
					this.currentMarker = e.target
					const info = e.target.options
					const geocode = new T.Geocoder()
					this.windowInfo = {
						name: info.name,
						id: info.id,
						address: '加载中...',
						lnglat: e.lnglat
					}
					const el = this.$refs.wInfo
					marker.openInfoWindow(el);
					geocode.getLocation(e.lnglat, (result) =>{
						if(result.getStatus() == 0){
							this.windowInfo.address = result.getAddress()
						}
					})
				})
				arrayObj.push(marker)
			}
			this.markerList = arrayObj
			this.markerMap = new T.MarkerClusterer(this.map, {markers: arrayObj})
		},
		initMap() {
			if(!this.map){
				const map = new T.Map('map', {
					attributionControl: false,
					inertia: false
				})
				window.map = map
				this.map = map
				this.initDrawTool()
			}
			this.map.centerAndZoom(new T.LngLat(120.651860, 27.781680), 6)
			this.map.enableDrag()
			// 测试数据
			this.addTestData()
		},
		// 初始化绘制工具
		initDrawTool() {
			// 矩形选择工具
			this.rectTool = new T.RectangleTool(
				this.map,
				{ color: "blue", weight: 2, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5}
			)
			this.rectTool.on('draw', (e) => {
				this.draw = false // 修改绘制状态，因其绘制后会自动关闭
				this.resetData()
				this.selectMarkers = []
				this.markerList.forEach(item =>{
					if(e.currentBounds.contains(item.or)){ // 判断点是否在矩形内
						this.setDataInfo(item)
					}else if(item.getIcon().options.id){
						item.setIcon(this.defaultIcon)
					}
				})
			})
			// 圆形选择工具
			this.circleTool = new T.CircleTool(
				this.map,
				{ color: "blue", weight: 2, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5}
			)
			this.circleTool.on('drawend', (e) => {
				this.draw = false // 修改绘制状态，因其绘制后会自动关闭
				this.resetData()
				this.selectMarkers = []
				this.markerList.forEach(item =>{
					if(e.currentCenter.distanceTo(item.or) <= e.currentRadius){ // 判断点是否在圆内
						this.setDataInfo(item)
					}
				})
			})
			const config = {
				showLabel: false,
				color: "blue", weight: 2, opacity: 0.5, fillColor: "#FFFFFF", fillOpacity: 0.5
			}
			// 多边形选择工具
			this.polygonTool = new T.PolygonTool(this.map, config)
			this.polygonTool.on('draw', (e) => {
				this.draw = false // 修改绘制状态，因其绘制后会自动关闭
				this.resetData()
				this.selectMarkers = []
				this.markerList.forEach(item =>{
					const isInside = this.insidePolygon(e.currentLnglats, item.or) // 判断点是否在多边形内
					if(isInside){
						this.setDataInfo(item)
					}
				})
			})
		},
		// 把框选的数据加入列表并修改图标
		setDataInfo(item){
			const obj = {
				...item.options,
				_checked: false
			}
			this.tableData.push(obj)
			// 选中修改图标
			const icon = new T.Icon({
				iconUrl: require('./img/marker_blue.svg'),
				iconSize: new T.Point(30, 46),
				iconAnchor: new T.Point(14, 41),
				id: item.options.id
			})
			item.setIcon(icon)
			this.selectMarkers.push(item)
		},
		// 判断点是否在多边形内
		insidePolygon(posArray, point){  
			let x = point.lng, y = point.lat
			let inside = false
			for (let i = 0, j = posArray.length - 1; i < posArray.length; j = i++) {  
				let xi = posArray[i].lng, yi = posArray[i].lat
				let xj = posArray[j].lng, yj = posArray[j].lat
				let intersect = ((yi > y) != (yj > y)) && (x < (xj - xi) * (y - yi) / (yj - yi) + xi)
				if (intersect) inside = !inside
			}  
			return inside
		},
		drawChange(val){
			const drawType = this.editType
			this[this.lastDrawType].clear()
			this.lastDrawType = drawType // 保存上一次绘制类型
			this.resetData()
			this.selectMarkers.forEach(item =>{
				if(item.getIcon().options.id){
					item.setIcon(this.defaultIcon)
				}
			})
			this.selectMarkers = []
			if(val){
				this[drawType].open()
			}else {
				this[drawType].close()
			}
		},
		editTypeChange(val) {
			this[this.lastDrawType].clear()
			this[this.lastDrawType].close()
			// this.lastDrawType = val // 保存上一次绘制类型
			this.resetData()
			this.selectMarkers.forEach(item =>{
				if(item.getIcon().options.id){
					item.setIcon(this.defaultIcon)
				}
			})
			if(this.draw){
				this[val].open()
			}
		},
		// 列表勾选
		onSelectChange (selection) {
			console.log(selection)
		  this.selectedData = selection
			this.selectMarkers.forEach(mItem =>{
				let id = mItem.getIcon().options.id
				let isSelect = false
				selection.forEach(item =>{
					if(id === item.id){
						isSelect = true
					}
				})
				const icon = new T.Icon({
					iconUrl: require('./img/marker_blue.svg'),
					iconSize: new T.Point(30, 46),
					iconAnchor: new T.Point(14, 41),
					id: id
				})
				if(isSelect){
					let iconUrl = require('./img/marker_red.svg')
					icon.setIconUrl(iconUrl)
				}
				mItem.setIcon(icon)
			})
		}
  }
}
</script>

<style>
	.content{
		display: flex;
		padding: 20px;
	}
	.left{
		width: 360px;
	}
	.right{
		flex: 1;
		margin-left: 20px;
	}
	.map-content{
		height: 100%;
		width: 100%;
		position: relative;
	}
	.clear-btn{
		background-color: #fff;
		width: 24px;
		height: 28px;
		padding: 5px;
		border: 1px solid #999;
		cursor: pointer;
	}
	.clear-btn img{
		width: 100%
	}
	#map{
		height: 100%;
		width: 100%;
	}
	.tdt-touch .tdt-control-copyright{
		display: none;
	}
	.tdt-infowindow-content{
		min-width: fit-content;
		margin: 0;
	}
	.w-info{
		font-size: 13px;
		border: 1px solid #ccc;
		min-width: 200px;
	}
	.w-info li{
		display: flex;
		align-items: center;
		margin-bottom: 5px;
		padding: 0 10px;
	}
	.t-name{
		border-bottom: 2px solid #666;
	}
	.w-text{
		margin-left: 10px;
	}
	.ivu-icon{
		font-size: 24px;
	}
	.ivu-icon-ios-search{
		color: #00c2ff;
	}
	.bm-control{
		position: absolute;
		top: 10px;
		left: 10px;
		z-index: 2000;
	}
	.drawToggle{
		height: 30px;
		background: #fff;
		margin-left: 10px;
		line-height: 30px;
		padding: 0 10px;
		border: 1px solid #d8dee5;
	}
	.sec-title{
		color: #333;
		font-size: 13px;
		font-weight: 700;
		margin-bottom: 10px;
	}
</style>